package br.feevale.ihc.seguranca

import static br.com.insoft4.json.utils.JsonUtils.*
import grails.plugins.springsecurity.Secured

import org.springframework.validation.Errors
import org.springframework.validation.FieldError
import org.springframework.web.servlet.support.RequestContextUtils as RCU

import br.com.insoft4.framework.commands.TrocarSenhaCommand
import br.com.insoft4.security.FwInsoftSecurityHelper

class UserSecurityController {

	def fwUserSecurityService
	
	def springSecurityService

	def sendNewPassword() {

		Map userConfig = FwInsoftSecurityHelper.getUserConfig()

		String userName = params.username
		String userEmail = params.email

		Locale locale = RCU.getLocale(request)
		
		def usuario = fwUserSecurityService.getUserForgotPassword(userName, userEmail, locale)

		if (usuario && usuario."${userConfig.email}") {

			String email = usuario."${userConfig.email}"

			String message = g.message(code: "default.message.emailEnviado", args: [email], default: "E-mail enviado para ${email}.")

			render contentType: 'application/json', text: toJson([success: true, message: message])
			
		} else {

			String message = g.message(code: "default.message.emailNaoEncontrado", default: "E-mail não encontrado.")
			render contentType: 'application/json', text: toJson([success: false, message: message])
		}
	}

	@Secured('IS_AUTHENTICATED_FULLY')
	def modifyPasswordConfirm(TrocarSenhaCommand command) {

		def errors = fwUserSecurityService.trocarSenhaUsuario(command)

		Locale locale = RCU.getLocale(request)
		
		if(errors) {
			render contentType: 'application/json', text: toJson([success: false, errors: errorsToResponse(errors)])
		} else {
			String message = g.message(code: "default.message.senhaAlteradaComSucesso", default: "Senha alterada com sucesso!")
			render contentType: 'application/json', text: toJson([success: true, message: message])
		}
	}
	
	protected List<Map> errorsToResponse(Errors errors) {
		return errorsToMap(errors)
	}
	
}
